﻿import bpy
from bpy.app.handlers import persistent
#use window / toogle system console

# 中文咋啦？
#this func can change render engine setting
def init_rendersetting():
    print("--py-- script bake.")

    nowengine = bpy.data.scenes["Scene"].render.engine;
    print("current render engine=" + nowengine);
    bpy.data.scenes["Scene"].render.engine = "CYCLES"
    nowengine = bpy.data.scenes["Scene"].render.engine;
    print("change render engine =>" + nowengine);


    n = bpy.data.scenes["Scene"].cycles.device;
    print("current cycles device=" + n);
    bpy.data.scenes["Scene"].cycles.device = "GPU";
    n = bpy.data.scenes["Scene"].cycles.device;
    print("change cycles device=>" + n);
    
#this func can execute bake
def bake():
    
    @persistent
    def handler_1(dummy):
        print("==handler_1")
    
    @persistent
    def handler_2(dummy):
        print("==handler_2")
        
    bpy.app.handlers.object_bake_pre.append(handler_1)
    bpy.app.handlers.object_bake_complete.append(handler_2)

    baketype = bpy.data.scenes["Scene"].cycles.bake_type;
    print("baketype=" + baketype);
    bpy.data.scenes["Scene"].cycles.bake_type="DIFFUSE";
    baketype = bpy.data.scenes["Scene"].cycles.bake_type;
    print("change cycles device=>" + baketype);
    
    pickmeshs();

    #回调在静默模式收不到
    #bpy.ops.object.bake('INVOKE_DEFAULT');
    bpy.ops.object.bake();


#this func can pick all mesh     
def pickmeshs():
    
    bpy.ops.object.select_all(action='DESELECT')#取消选择
    objs=list(filter(lambda obj: obj.type == 'MESH', bpy.data.objects))


    for i in objs:


        i.select_set(True);
        bpy.ops.export_mesh.stl
    


#this is where is lightmap
def checklightmap():

    img = bpy.data.images["lightmap"];
    print(img.filepath) 
    print(img.file_format)

#打开默认场景用
def loadscene():

    bpy.ops.wm.open_mainfile(filepath="d:\\temp\\1.blend");
    print("==load matbake scene");

#替换材质
def givemat():
   
    bpy.ops.object.select_all(action='DESELECT')#取消选择
    objs=list(filter(lambda obj: obj.type == 'MESH', bpy.data.objects))
    
    _bakemat = bpy.data.materials["matbake"];
    for i in objs:
        
        i.data.materials.append(_bakemat);

    print("==givemat");
    
def packuv():
    pickmeshs();     

    bpy.ops.object.editmode_toggle()
    bpy.ops.mesh.select_all(action='SELECT')
    bpy.ops.uv.smart_project();
   
    bpy.ops.uv.lightmap_pack(PREF_CONTEXT='ALL_FACES',PREF_IMG_PX_SIZE=2048, PREF_BOX_DIV=12, PREF_MARGIN_DIV=0.2);

    bpy.ops.object.editmode_toggle()
    print("==packuv");

def savelightmap():
    _settings = bpy.context.scene.render.image_settings
    _old_format = _settings.file_format
    _old_quality = _settings.quality
    _settings.file_format = 'OPEN_EXR'



    img = bpy.data.images["lightmap"];
    img.save_render("d:\\temp\\out.exr");

    _settings.file_format = _old_format
    _settings.quality = _old_quality

    print("==savelightmap");


def writeobjinfo(obj):
    _name =obj.name;
    with open("d:\\temp\\outmesh\\"+_name+".info.txt","w") as f:
        
        _pos =obj.location;
        _posstr = str(_pos.x)+","+str(_pos.y)+","+str(_pos.z)+"\n";
       
        _rot =obj.rotation_euler;
        _rotstr = str(_rot.x)+","+str(_rot.y)+","+str(_rot.z)+"\n";
        
        _scale =obj.scale;
        _scalestr = str(_scale.x)+","+str(_scale.y)+","+str(_scale.z)+"\n";
        
        f.write(_posstr);
        f.write(_rotstr);
        f.write(_scalestr);

def exportobjs():
   
    objs=list(filter(lambda obj: obj.type == 'MESH', bpy.data.objects))
    for i in objs:
        
        bpy.ops.object.select_all(action='DESELECT')#取消选择
        i.select_set(True);
        bpy.ops.export_mesh.ply(filepath="d:\\temp\\outmesh\\"+i.name+".ply",check_existing=False,use_selection=True,use_ascii=True);
        writeobjinfo(i);

    bpy.ops.object.select_all(action='DESELECT')#取消选择


import mathutils;

def importobj(path,file):
    
    _objset = bpy.ops.import_mesh.ply(filepath=path+file+".ply");
    _obj = bpy.data.objects[file];
    
    with open(path+file+".info.txt") as f:
        _posline = f.readline().split(',');
        _rotline = f.readline().split(',');
        _scaleline = f.readline().split(',');
        
        _pos = mathutils.Vector();
        _pos.x =float(_posline[0]);
        _pos.y =float(_posline[1]);
        _pos.z =float(_posline[2]);
        _obj.location = _pos;
        
        _rot = mathutils.Vector();
        _rot.x =float(_rotline[0]);
        _rot.y =float(_rotline[1]);
        _rot.z =float(_rotline[2]);
        _obj.rotation_euler = _rot;
        
        _scale = mathutils.Vector();
        _scale.x =float(_scaleline[0]);
        _scale.y =float(_scaleline[1]);
        _scale.z =float(_scaleline[2]);
        _obj.scale = _scale;
        
    print("importobj:"+file);
    
def cleanobjs():

    objs=list(filter(lambda obj: obj.type == 'MESH', bpy.data.objects))
    for i in objs:
        i.select_set(True);
        bpy.ops.object.delete();
    bpy.ops.object.select_all(action='DESELECT')#取消选择
        
import os;   
def importobjs():
    cleanobjs();
    for file in os.listdir("d:\\temp\\inmesh"):
        if file.endswith(".ply"):
            importobj("d:\\temp\\inmesh\\",file[:-4]);

#init_rendersetting();
#bake();